const HtmlWebpackPlugin = require("html-webpack-plugin");

class ReplaceAttributeWebpackPlugin {
  constructor(options) {
    this.options = Object.assign({}, options)
  }

  apply(compiler) {
    const skip = data => {
      const htmlFilename = data.plugin.options.filename
      const exclude = this.options.excludeHtmlNames
      const include = this.options.includeHtmlNames
      return (
        (include && !(include.includes(htmlFilename))) ||
        (exclude && exclude.includes(htmlFilename))
      )
    }

    compiler.hooks.compilation.tap(
      this.constructor.name,
      compilation => {
        //  compilation.hooks.htmlWebpackPluginAlterAssetTags.tap(
        const hooks = HtmlWebpackPlugin.getCompilationHooks(compilation)
        hooks.alterAssetTags.tap(
          this.constructor.name,
          (data) => {
            if (skip(data)) {
              return
            }

            let replaceAction = (item) => {
              if (typeof item === "object" && typeof this.options === "object") {
                let config = Object.assign({}, item)
                let attributes = config.attributes
                if (typeof attributes === "object") {
                  Object.keys(attributes).forEach((key) => {
                    let value = attributes[key]
                    if (typeof this.options[key] === "function") {
                      delete attributes[key]
                      let results = this.options[key](key, value)
                      if (results instanceof Array) {
                        attributes[results[0]] = results[1]
                      } else {
                        attributes[results] = value
                      }
                    }
                    if (typeof this.options[key] === "string") {
                      delete attributes[key]
                      attributes[this.options[key]] = value
                    }
                  })
                  config.attributes = attributes
                }
                return config
              }
              return item
            }

            data.assetTags.scripts = data.assetTags.scripts.map(replaceAction)
            data.assetTags.styles = data.assetTags.styles.map(replaceAction)
            return data
          }
        )
      }
    )
  }
}

module.exports = ReplaceAttributeWebpackPlugin
